import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:top_foundation/top_foundation.dart';
import 'package:regular_assess/helper/utils/ifly/ifly_util.dart';

import '../../helper/utils/util.dart';
import 'index.dart';

class WebViewPage extends GetView<WebController> {
  const WebViewPage({Key? key}) : super(key: key);

  // 主视图
  Widget _buildView() {
    // var ctrl = controller.state.webCtrl;

    // Get.log(ctrl.isBlank.toString());
    // return WebViewWidget(controller: controller.state.webCtrl);
    var state = controller.state;
    if (state.url == null) {
      return const SizedBox();
    }
    return InAppWebView(
      initialUrlRequest: URLRequest(
        url: WebUri(state.url!),
        allowsCellularAccess: true,
      ),
      onReceivedServerTrustAuthRequest: (controller, challenge) async {
        return ServerTrustAuthResponse(
            action: ServerTrustAuthResponseAction.PROCEED);
      },
      onReceivedHttpAuthRequest: (controller, challenge) {
        return Future.value(
            HttpAuthResponse(action: HttpAuthResponseAction.PROCEED));
      },
      onWebViewCreated: (webCtrl) async {
        state.webCtrl = webCtrl;
        webCtrl.addJavaScriptHandler(
          handlerName: 'onRecord',
          callback: (arguments) {
            controller.onRecord();
          },
        );
        webCtrl.addJavaScriptHandler(
          handlerName: 'getUser',
          callback: (arguments) {
            controller.getUser();
          },
        );
        webCtrl.addJavaScriptHandler(
          handlerName: 'logOut',
          callback: (arguments) {
            controller.logOut();
          },
        );
        webCtrl.addJavaScriptHandler(
          handlerName: 'getName',
          callback: (arguments) {
            Get.log('getName------$arguments');
          },
        );
      },
      onTitleChanged: (webCtrl, title) {
        controller.pageFinished();
      },
      onLoadStart: (controller, url) {
        Hud.show();
      },
      onLoadStop: (controller, url) async {
        Hud.dismiss();
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<WebController>(
      builder: (_) {
        return WillPopScope(
          onWillPop: !controller.state.isWebCanBack
              ? null
              : () async {
                  if (await IFlyUtil().record.isRecording()) {
                    return false;
                  }

                  return true;
                },
          child: Scaffold(
            appBar: controller.state.title == null
                ? null
                : detailAppBar(context, title: controller.state.title),
            body: controller.state.isSafeArea
                ? SafeArea(
                    child: _buildView(),
                  )
                : _buildView(),
          ),
        );
      },
    );
  }
}
